//
//  RegisterViewController.m
//  SelfDriving
//
//  Created by apple on 16/1/8.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "RegisterViewController.h"
#import "BusinessService+User.h"
#import "RegisterSViewController.h"
#import "UIChooseTableView.h"
#import "ValidateHelper.h"
@interface RegisterViewController ()<UIChooseTableViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneField;
@property (weak, nonatomic) IBOutlet UITextField *codeField;
@property (weak, nonatomic) IBOutlet UITextField *pwdField;
@property (weak, nonatomic) IBOutlet UILabel *quhao;
@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;
@property (nonatomic,assign) int timerNum;
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, copy) NSString * code;
@property (nonatomic, strong)UIColor *codeColor;

@end

@implementation RegisterViewController
{
    UIChooseTableView *chooseTabel;
    NSString *quhao;
    NSMutableArray *hmdata;
}

- (void)viewDidDisappear:(BOOL)animated {
    [_timer invalidate];
    _timer = nil;
    
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    _timerNum = 60;
    
    UIColor * codeBtnColor = self.getCodeBtn.backgroundColor;
    _codeColor = codeBtnColor;
    self.navigationController.navigationBar.translucent=YES;
    [AppDelegate shareDelegate].isScollBack = NO;
    hmdata = [[NSMutableArray alloc]init];
    [[BusinessService shareInstance]haoma:[[NSMutableDictionary alloc]init] success:^(id result) {
        hmdata = result;
        _quhao.text = [[hmdata firstObject] objectForKey:@"code"];
        NSMutableArray *data = [[NSMutableArray alloc]init];
        for (int i = 0; i<hmdata.count; i++) {
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
            [dic setObject:[[hmdata objectAtIndex:i] objectForKey:@"code"] forKey:@"id"];
            [dic setObject:[[hmdata objectAtIndex:i] objectForKey:@"name"] forKey:@"name"];
            [data addObject:dic];
        }
        hmdata = data;
    } failure:^(id result) {
    }];
    self.navigationController.navigationBarHidden = NO;
    _phoneField.delegate = self;
}
-(void)viewWillAppear:(BOOL)animated{
    
}
-(void)viewDidAppear:(BOOL)animated{
    [AppDelegate shareDelegate].isScollBack = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void)timerFun {
    _timerNum -= 1;
    [self.getCodeBtn setTitle:[NSString stringWithFormat:@"%d秒",_timerNum] forState:UIControlStateNormal];
    if (_timerNum == 0) {
        self.getCodeBtn.enabled = true;
        self.getCodeBtn.backgroundColor = _codeColor;//[UIColor colorWithRed:41 green:184 blue:42 alpha:1];
        [self.getCodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        _timerNum = 60;
        [_timer invalidate];
    }
}

- (IBAction)getCodeAction:(UIButton *)sender {
    if([_phoneField.text trim].length == 0 ){
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return;
    }
    else {
        if (![ValidateHelper isValidateMobile:_phoneField.text]) {
            [SVProgressHUD showErrorWithStatus:@"手机号格式不正确"];
            return;
        }
    }
    NSMutableDictionary *dic= [[NSMutableDictionary alloc]init];
    [dic setObject:[_phoneField.text trim] forKey:@"phone"];
    [dic setObject:@"0" forKey:@"type"];
    [[BusinessService shareInstance]getCode:dic success:^(id result) {
        NSString * code = [result objectForKey:@"code"];
        _code = code;
        [SVProgressHUD showSuccessWithStatus:@"获取验证码成功"];
        //xhw2018-3-9加
        _getCodeBtn.enabled = NO;
        _getCodeBtn.backgroundColor = [UIColor lightGrayColor];
        [_getCodeBtn setTitle:[NSString stringWithFormat:@"%d秒",_timerNum] forState:UIControlStateNormal];
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFun) userInfo:nil repeats:YES];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}
#pragma mark 选择区号
- (IBAction)xuanzhequhao:(UIButton *)sender {
    chooseTabel = [[UIChooseTableView alloc] initWithFrame:CGRectMake(0.0f, SCRE_HEIGHT, SCRE_WIDTH, 260.0f)];
    chooseTabel.delegate = self;
    chooseTabel.lanel_title.text = @"选择区号";
    chooseTabel.mainData  = hmdata;
    [chooseTabel up];
    [[[[UIApplication sharedApplication] windows] firstObject] addSubview:chooseTabel];
}
-(void)didSelectDate:(UITableView *)chooseTableView indexPath:(NSIndexPath *)indexPath string:(NSMutableDictionary *)string{
    _quhao.text  = [string objectForKey:@"id"];
    quhao = [string objectForKey:@"id"];
    
}
- (IBAction)registerAction:(UIButton *)sender {
    
//    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
//                                                                 bundle:[NSBundle mainBundle]];
//    RegisterSViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"RegisterSVC"];
//      [self.navigationController pushViewController:searchResultDetailController animated:YES];
//    return;
    
    if([_phoneField.text trim].length == 0 ){
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return;
    }
    else {
        if (![ValidateHelper isValidateMobile:_phoneField.text]) {
            [SVProgressHUD showErrorWithStatus:@"手机号格式不正确"];
            return;
        }
    }
    
    if([_codeField.text trim].length == 0 ){
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
        return;
    }
    if([_pwdField.text trim].length == 0 ){
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        return;
    }
    if (![ValidateHelper isMobileNum:_phoneField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码"];
        return;
    }

    if (_code) {
        if (!([_codeField.text intValue] == [_code intValue])) {
            [SVProgressHUD showErrorWithStatus:@"请输入正确的验证码"];
            return;
        }
    }
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[_pwdField.text trim] forKey:@"password"];
    [dic setObject:[_phoneField.text trim] forKey:@"phone"];
    [dic setObject:[_codeField.text trim] forKey:@"code"];
    [[BusinessService shareInstance] registered:dic success:^(id result) {
        LoginResponseModel *model = result;
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
                                                                     bundle:[NSBundle mainBundle]];
        RegisterSViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"RegisterSVC"];
        searchResultDetailController.dic = dic;
        searchResultDetailController.uid = [NSString stringWithFormat:@"%@",model.uid];
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
        
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
    
    
    
}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField isEqual:_phoneField]) {
        if ([string length] != 0) {
            UniChar single = [string characterAtIndex:0];
            if (single <= '9' && single >= '0') {
                return YES;
            }
            return NO;
        }
        return YES;
    }
    return YES;
}


@end
